extends Node2D

@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var collision_shape_2d: CollisionShape2D = $Area2D/CollisionShape2D

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	$Area2D.area_entered.connect(on_area_enter)

func tween_collect(percent: float, start_position:Vector2):
	var player = get_tree().get_first_node_in_group("player")
	if player == null:
		print("玩家为空")
		return 
	var target_position = player.global_position
	global_position = start_position.lerp(target_position, percent)
	
	var direction = global_position - start_position
	var target_angle = direction.angle() + deg_to_rad(90)
	rotation = lerp_angle(rotation, target_angle, percent)

func disable_collision():
	collision_shape_2d.disabled = true

func collect():
	GameEvent.emit_experience_vial_collected(1)
	queue_free()

@warning_ignore("unused_parameter")
func on_area_enter(otherArea: Area2D):
	# 这里是因为如果不禁用碰撞，会发生两次。
	# call_deferred的意思是 物理检测结束后调用这个函数
	Callable(disable_collision).call_deferred()
	var tween = create_tween()
	tween.set_parallel()
	# bind是可以额外添加的参数，然后后面两个是参数的变化返回从0-1 持续时间0.5秒
	# 这个变换的值会传入tween_collect的函数中
	tween.tween_method(tween_collect.bind(global_position), 0.0, 1.0, 0.6)\
		.set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_BACK)
	tween.tween_property(sprite_2d, "scale", Vector2.ZERO, .05).set_delay(.55)
	# 因为上面的动画是parallel平行的 这里调用chain 等上面平行的结束 在进行后面的。
	tween.chain()
	tween.tween_callback(collect)
